package com.itany.book.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.book.exception.ManagerUserNotExistsException;
import com.itany.book.mapper.ManagerUserMapper;
import com.itany.book.pojo.ManagerUser;
import com.itany.book.service.ManagerUserService;
import com.itany.book.vo.ResponseResult;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Author:yaozhiyuan0117@163.com
 * Time:2019/12/24 17:47
 * Describe:
 * version:1.0
 */


@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class ManagerUserServiceImpl implements ManagerUserService {

    @Autowired
    private ManagerUserMapper managerUserMapper;

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    public ManagerUser login(ManagerUser user) throws ManagerUserNotExistsException {
        ManagerUser u = managerUserMapper.selectByUsernameAndPassword(user);
        if(u==null){
            throw new ManagerUserNotExistsException("用户名或密码不正确");
        }
        return u;
    }

    @Override
    public void modifyPassword(ManagerUser user) {
        managerUserMapper.updatePassword(user);
    }

    @Override
    public PageInfo<ManagerUser> findAll(Integer page, Integer rows, String username) {
        PageHelper.startPage(page,rows);
        List<ManagerUser> users = managerUserMapper.selectByCondition(username);
        return new PageInfo<>(users);
    }

    public void  addUser(String username, String password, Integer[] roles){

        ManagerUser user = new ManagerUser();
        user.setUsername(username);
        user.setPassword(password);
        // 增加user
        managerUserMapper.insertUser(user);
        Integer userid = user.getId();
        // 增加user_role
        for (Integer roleId: roles){
            managerUserMapper.insertUserRole(userid, roleId);
        }
    }

    @Override
    public ManagerUser findById(Integer id) {
        return managerUserMapper.selectById(id);
    }

    @Override
    public void modifyUser(Integer id, String username, String password, Integer[] roles) {
        // 1.修改t_manager_user表
        managerUserMapper.updateManagerUser(id, username, password);

        // 2. 删除t_user_role
        managerUserMapper.deleteUserRoleById(id);

        // 3. 添加t_user_role
        for (Integer roleId: roles){
            managerUserMapper.addUserRoleById(id,roleId);
        }

    }
}
